#!/bin/bash

function usage {
    echo "usage: $0 rcfiles"
    exit 1
}

function link {
    file="$1"
    target="$dir/$file"
    name="$HOME/.$file"
    if [[ ! ( -f "$target" || -d "$target" ) ]]
    then
        echo "target $target does not exist"
        return
    fi
    read -p "create link: '$name' -> $target'? (yes/no/quit) " ans
    case $ans in
        [nN]*)
            ;;
        [qQ]*)
            exit;;
        *)
            # if the link name exists as a non-linked directory,
            # ln will not overwrite it, so we ask the user
            if [[ -d "$name" && ! -L "$name" ]]
            then
                read -p "remove directory '$name?' (yes/no/quit) " ans
                case $ans in
                    [nN]*)
                        return;;
                    [qQ]*)
                        exit;;
                    *)
                        rm -r "$name";;
                esac
            fi
            # create symbolic link, prompting before removing files, while
            # treating symbolic links to directories as files,
            # treating link names as files, not directories, and
            # printing names of linked files
            ln -sinTv "$target" "$name"
    esac
}

# get the dotfiles repository directory
dir="$(cd "$(dirname "$0")" && pwd)"
cd $dir

if [[ "$#" == 0 ]]
then
    usage
fi

for file in "$@"
do
    # we do not want to link to the install file
    if [[ "$file" == "install.sh" ]]
    then
        continue
    fi
    link "$file"
done
